package com.sfy.designdemo.singleton;

/**
 * Created by SiFeiYang on Date 2022/7/11
 */
public class Singleton {
    //懒汉式
   /* private static Singleton instance;
    private Singleton (){}
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }*/


    //饿汉式
    /*private static Singleton instance = new Singleton();
    private Singleton (){}
    public static Singleton getInstance() {
        return instance;
    }*/


//静态内部类式
   /* private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }*/

    //双锁检验
/*    private volatile static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }*/
}
//使用枚举，最佳方式
class InstanceDemo {

    /**
     * 构造方法私有化
     */
    private InstanceDemo(){

    }

    /**
     * 返回实例
     * @return
     */
    public static InstanceDemo getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    /**
     * 使用枚举方法实现单例模式
     */
    private enum Singleton {//内部枚举类
        INSTANCE;

        private InstanceDemo instance;

        /**
         * JVM保证这个方法绝对只调用一次
         */
        Singleton() {
            instance = new InstanceDemo();
        }

        public InstanceDemo getInstance() {
            return instance;
        }
    }
}
